package com.paypalpay.controller.interfaces;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.paypalpay.entity.common.DevicePackageCoverPicture;
import com.paypalpay.entity.common.DevicePackageMarketingStrategy;
import com.paypalpay.entity.common.InternationalPayPackage;
import com.paypalpay.entity.common.TrafficExpressCostManage;
import com.paypalpay.external.entity.packages.request.RequestPackage;
import com.paypalpay.external.entity.packages.request.RequestPackageData;
import com.paypalpay.external.entity.packages.response.ResponsePackage;
import com.paypalpay.external.entity.packages.response.ResponsePackageCoverCountry;
import com.paypalpay.external.entity.packages.response.ResponsePackageData;
import com.paypalpay.external.entity.packages.response.ResponsePackageTradeData;
import com.paypalpay.external.utils.UtilsInterfacesPackage;
import com.paypalpay.service.InternationalPayPackageService;
import com.paypalpay.service.SequenceService;
import com.paypalpay.service.TrafficExpressCostService;
import com.paypalpay.util.wx.MD5;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 前端商城获取设备套餐信息的类，首页
 *
 * @author lm
 * @date 2018/8/30
 */
@RestController
@Api(description = "前端商城获取首页接口")
public class GetDeviceHomePageController {

    @Autowired
    private HttpSession session;
    @Autowired
    private SequenceService sequenceService;
    @Autowired
    private InternationalPayPackageService internationalPayPackageService;
    @Autowired
    private TrafficExpressCostService trafficExpressCostService;
    //进入领科H5的一般都是卖卡的，给一个固定的deviceType值为4：物联网卡
    private String deviceType="4";
    @CrossOrigin
    @RequestMapping(value = "getDeviceHomepage", produces = "application/json;charset=utf-8", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "领科商城首页", response = ResponsePackage.class)
    public String getDevicePackage(@ApiParam @RequestBody RequestPackage requestPackage) {
        // 1，生成流水号
        String ConnSeqNo = sequenceService.getPackageTaskNo();
        // 2,生成当前时间戳
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String curtime = df.format(new Date());
        // 1，生成用户id的流水号
        String userId = sequenceService.getUserId();
        String requestStr = JSON.toJSONString(requestPackage);
        System.out.println("前端请求报文是：" + requestStr);

        String openId = (String) session.getAttribute("openId");
        System.out.println("从session取出的openId是：" + session.getAttribute("openId"));

        UtilsInterfacesPackage utils = new UtilsInterfacesPackage();
        requestPackage = JSONArray.parseObject(requestStr, RequestPackage.class);
        String requestSign = requestPackage.getSign();
        System.out.println("请求的签名是：" + requestSign);
        if (requestPackage.getSign() == null) {
            System.out.println("请求报文不合法:sign为空");
            String jsonString = utils.dataWeiKong(ConnSeqNo, curtime);
            return jsonString;
        } else {
            RequestPackageData requestData = requestPackage.getData();
            if (requestPackage.getData() == null) {
                System.out.println("请求报文不合法:data为空");
                String jsonString = utils.dataWeiKong(ConnSeqNo, curtime);
                return jsonString;
            } else {
                String partnerCode = requestData.getPartnerCode();
                String connSeqNo = requestData.getConnSeqNo();
                String token = requestData.getToken();
                String tradeTime = requestData.getTradeTime();
                String tradeType = requestData.getTradeType();
                //获取到前端请求的lang的语言 en/cn
                String lang = requestData.getLang();
                String deviceId=requestData.getDeviceId();

                if (connSeqNo == null || connSeqNo.length() <= 0 || token == null || token.length() <= 0 || tradeTime == null || tradeTime.length() <= 0 || lang == null || lang.length() <= 0||deviceId==null||deviceId.length()<=0) {
                    //参数不全,回复报文
                    System.out.println("请求报文不合法:参数不全！");
                    String jsonString = utils.dataWeiKong(ConnSeqNo, curtime);
                    return jsonString;
                } else {
                    // 将请求体json转成String
                    String str = JSON.toJSONString(requestData);
                    // 将Str拿去计算签名
                    String sign = utils.calculateSignature(str);
                    System.out.println("计算的签名是：" + sign);
                    // 验证签名：
                    if (!requestSign.equalsIgnoreCase(sign)) {
                        // 如果收到的签名跟算出的签名相同才可以回复正确的报文
                        System.out.println("请求报文签名验证失败");
                        String jsonString = utils.signatureFailMessage(connSeqNo, tradeTime, partnerCode, token, deviceId, deviceType);
                        return jsonString;
                    } else {
                        String partner_Code="";
                        String packageCode = "";
                        String packageName = "";
                        String packageNameEN = "";
                        String orderUnit = "";
                        String orderPeriod = "";
                        String pictureIndex = "";
                        String pictureDetails = "";
                        String strategyCode = "";
                        String salePriceCNY="";
                        String salePriceUSD="";
                        String strategyDescCNY="";
                        String strategyDescUSD="";
                        String coverCountryMcc = "";
                        String continentName = "";
                        String continentNameEN = "";
                        String countryNameIndex = "";
                        String countryNameIndexEN = "";
                        String trafficCardfee = "";
                        String ordinaryExpressfee = "";
                        String sFexpressfee = "";
                        String orderFullX = "";

                        List<ResponsePackageTradeData> tradeData = new ArrayList<ResponsePackageTradeData>();
                        ResponsePackageTradeData trade = null;
                        // 1,从PartnerPackage数据库把数据取出来
                        List<InternationalPayPackage> packagesList = internationalPayPackageService.queryPackages(partnerCode,deviceId);
                        //List<InternationalPayPackage> packagesList = internationalPayPackageService.queryPackages();
                        // 把从数据库取到的值循环遍历出来并循环赋给对象
                        for (InternationalPayPackage p : packagesList) {
                            partner_Code=p.getPartnerCode();
                            packageCode = p.getPackageCode();
                            packageName = p.getPackageName();
                            packageNameEN = p.getPackageNameEN();
                            orderUnit = p.getOrderUnit();
                            orderPeriod = p.getOrderPeriod();
                            coverCountryMcc = p.getCoverCountryMcc();
                            countryNameIndex = p.getCountryNameIndex();
                            countryNameIndexEN = p.getCountryNameIndexEN();
                            continentName = p.getContinentName();
                            continentNameEN = p.getContinentNameEN();

                            // 1,从CoverPicture表中把图片信息取出来 ,packageCode,partnerCode
                            List<DevicePackageCoverPicture> pictureList = internationalPayPackageService.queryPictureInfo(packageCode, partner_Code);
                            for (DevicePackageCoverPicture covers : pictureList) {
                                pictureIndex = covers.getPictureIndex();
                                pictureDetails = covers.getPictureDetails();
                            }

                            // 2,从PackageMarketingStrategy表中把营销信息取出来 ,partnerCode
                            List<DevicePackageMarketingStrategy> strategyList = internationalPayPackageService.queryDeviceStrategy(packageCode, partner_Code);
                            for (DevicePackageMarketingStrategy strategy : strategyList) {
                                strategyCode = strategy.getStrategyCode();
                                salePriceCNY=strategy.getSalePriceCNY();
                                salePriceUSD=strategy.getSalePriceUSD();
                                strategyDescCNY=strategy.getStrategyDescCNY();
                                strategyDescUSD=strategy.getStrategyDescUSD();
                            }

                            //3,将卡费快递费取出来
                            List<TrafficExpressCostManage> trafficList = trafficExpressCostService.getCostInfo();
                            for (TrafficExpressCostManage info : trafficList) {
                                trafficCardfee = info.getTrafficCardfee();
                                ordinaryExpressfee = info.getOrdinaryExpressfee();
                                sFexpressfee = info.getSFexpressfee();
                                orderFullX = info.getOrderFullX();
                            }
                            // 之前不作处理coverCountry时，给coverCountry赋值：
                            List<ResponsePackageCoverCountry> coverCountryList = new ArrayList();
                            ResponsePackageCoverCountry cover = new ResponsePackageCoverCountry();
                            cover.setMcc(coverCountryMcc);
                            //将原来展示国家的位置现在改成文字描述（首页）比如，新马泰
                            cover.setCountryName(countryNameIndex);
                            //为了解决39个国家continentName大洲名字就有39个欧洲，就显示一个欧洲
                            if (lang.equals("en")) {
                                cover.setCountryName(countryNameIndexEN);
                                if (continentNameEN != null && !"".equals(continentNameEN)) {
                                    String continent = continentNameEN.split(",")[0];
                                    cover.setContinentName(continent);
                                }
                            } else {
                                cover.setCountryName(countryNameIndex);
                                if (continentName != null && !"".equals(continentName)) {
                                    String continent = continentName.split(",")[0];
                                    cover.setContinentName(continent);
                                }
                            }
                            coverCountryList.add(cover);
                            // 5,给TradeData赋值
                            trade = new ResponsePackageTradeData();
                            trade.setUserId(userId);

                            if (openId == null) {
                                trade.setOpenId("");
                                if (deviceId == null && deviceType == null) {
                                    trade.setDeviceId("");
                                    trade.setDeviceType("");
                                    trade.setDeviceTypeText("");
                                } else {
                                    trade.setDeviceId(deviceId);
                                    trade.setDeviceType(deviceType);
                                    //用type去匹配TypeText
                                    if (lang.equals("cn")) {
                                        if (deviceType.equals("2")) {
                                            trade.setDeviceTypeText("模块");
                                        } else if (deviceType.equals("4")) {
                                            trade.setDeviceTypeText("物联网卡");
                                        } else if (deviceType.equals("5")) {
                                            trade.setDeviceTypeText("SOC");
                                        } else if (deviceType.equals("1")) {
                                            trade.setDeviceTypeText("MIFI设备");
                                        } else if (deviceType.equals("3")) {
                                            trade.setDeviceTypeText("旅游卡");
                                        }
                                    } else {
                                        if (deviceType.equals("2")) {
                                            trade.setDeviceTypeText("MODAL");
                                        } else if (deviceType.equals("4")) {
                                            trade.setDeviceTypeText("M2M");
                                        } else if (deviceType.equals("5")) {
                                            trade.setDeviceTypeText("SOC");
                                        } else if (deviceType.equals("1")) {
                                            trade.setDeviceTypeText("MIFI");
                                        } else if (deviceType.equals("3")) {
                                            trade.setDeviceTypeText("CARD");
                                        }
                                    }
                                }
                            } else {
                                trade.setOpenId(openId);
                                if (deviceId == null && deviceType == null) {
                                    trade.setDeviceId("");
                                    trade.setDeviceType("");
                                    trade.setDeviceTypeText("");
                                } else {
                                    trade.setDeviceId(deviceId);
                                    trade.setDeviceType(deviceType);
                                    //用type去匹配TypeText
                                    if (lang.equals("cn")) {
                                        if (deviceType.equals("2")) {
                                            trade.setDeviceTypeText("模块");
                                        } else if (deviceType.equals("4")) {
                                            trade.setDeviceTypeText("物联网卡");
                                        } else if (deviceType.equals("5")) {
                                            trade.setDeviceTypeText("SOC");
                                        } else if (deviceType.equals("1")) {
                                            trade.setDeviceTypeText("MIFI设备");
                                        } else if (deviceType.equals("3")) {
                                            trade.setDeviceTypeText("旅游卡");
                                        }
                                    } else {
                                        if (deviceType.equals("2")) {
                                            trade.setDeviceTypeText("MODAL");
                                        } else if (deviceType.equals("4")) {
                                            trade.setDeviceTypeText("M2M");
                                        } else if (deviceType.equals("5")) {
                                            trade.setDeviceTypeText("SOC");
                                        } else if (deviceType.equals("1")) {
                                            trade.setDeviceTypeText("MIFI");
                                        } else if (deviceType.equals("3")) {
                                            trade.setDeviceTypeText("CARD");
                                        }
                                    }
                                }
                            }

                            //======================================
                            trade.setPackageCode(packageCode);
                            if (lang.equals("en")) {
                                trade.setPackageName(packageNameEN);
                            } else {
                                trade.setPackageName(packageName);
                            }
                            trade.setOrderUnit(orderUnit);
                            trade.setOrderPeriod(orderPeriod);
                            trade.setPictureIndex(pictureIndex);
                            trade.setPictureDetails(pictureDetails);
                            // 将覆盖国家信息加入进去了
                            trade.setCoverCountry(coverCountryList);
                            trade.setStrategyCode(strategyCode);
                            // strategyCode取值：1,热销商品；2,低价促销；3，为正常销售；4既是热销又是低价促销

                            if ("en".equalsIgnoreCase(lang)) {
                                if (strategyCode.equals("1") || strategyCode.equals("3")) {
                                    trade.setSalePrice(salePriceUSD);
                                } else if (strategyCode.equals("2") || strategyCode.equals("4")) {
                                    trade.setStrategyDesc(strategyDescUSD);
                                }
                            } else {
                                if (strategyCode.equals("1") || strategyCode.equals("3")) {
                                    trade.setSalePrice(salePriceCNY);
                                } else if (strategyCode.equals("2") || strategyCode.equals("4")) {
                                    trade.setStrategyDesc(strategyDescCNY);
                                }
                            }

                            tradeData.add(trade);
                        }
                        // 以上循环结束。
                        // 6，给Data赋值
                        ResponsePackageData data = new ResponsePackageData();
                        data.setTrafficCardfee(trafficCardfee);
                        data.setOrdinaryExpressfee(ordinaryExpressfee);
                        data.setSFexpressfee(sFexpressfee);
                        data.setOrderFullX(orderFullX);
                        data.setConnSeqNo(ConnSeqNo);
                        data.setPartnerCode(partner_Code);
                        data.setToken(token);
                        data.setTradeType(tradeType);
                        data.setTradeTime(curtime);
                        data.setTradeRstCode(1000);
                        data.setTradeRstMessage("success");
                        data.setTradeData(tradeData);

                        // 6，给ResponsePackage赋值
                        ResponsePackage resPackages = new ResponsePackage();
                        resPackages.setData(data);
                        resPackages.setSign(MD5.calcMD5(JSON.toJSONString(data)));
                        // 返回给调用者的报文
                        String jsonString = JSON.toJSONString(resPackages);
                        System.out.println("响应报文：" + jsonString);
                        return jsonString;
                    }
                }
            }
        }
    }
}